/**
 * 角色页
 */
import React from 'react';
import { connect } from 'dva';
import Table from './table';
import Filter from './filter';
import shouldComponentUpdate from '../../components/decorator/shouldComponentUpdate';
import showInHeader from '../../components/decorator/showInHeader';
import { Modal } from 'antd';


// const firstList=[
//   {"imei":"869858033135279"},{"result":2},{"pollutionFault":"暂无数据"},{"staticPointFault":"暂无数据"},{"detectorLossFault":"false"},{"fireAlarm":"false"},{"selfChecking":"true"},{"analogQuantity":"暂无数据"},{"temperature":"27"},{"rssi":"暂无数据"},{"undervoltageFault":""},{"undervoltageFaultModule":"暂无数据"},{"wirelessmoduleVersion":"暂无数据"},{"modulesoftwareVersion":"暂无数据"},{"deviceVersion":"暂无数据"},{"wirelessmoduleElectricity":"暂无数据"},{"componetType":"暂无数据"},{"deviceStatus":"暂无数据"},{"devicesEvent":"暂无数据"},{"packNumber":"暂无数据"},{"iccid":"89860620050000289203"},{"controlOlder":"暂无数据"},{"batteryLevel":"100"},{"signalStrength":"-74"},{"signalSNR":"11"},{"signalECL":"0"},{"linkQuality":"暂无数据"},{"smokeConcentration":"0000"},{"sensitivity":"02"},{"manufacturer":"5"},{"normal":"暂无数据"},{"sensorFault":"false"},{"fault":"false"},{"batteryLow":"false"},{"statusTime":"15:48:49"},
// ]

@showInHeader(['productSelect'])
@shouldComponentUpdate



class ProductList extends React.Component {
	constructor(props, context) {
		super(props, context);
    const oQrcodeList = JSON.parse(localStorage.getItem('qrcodeList')) && JSON.parse(localStorage.getItem('qrcodeList')).length ? JSON.parse(localStorage.getItem('qrcodeList')) : [];
    const oProductKey = JSON.parse(localStorage.getItem('bindProInfo')).productKey ? JSON.parse(localStorage.getItem('bindProInfo')).productKey : '';
    const oProductName = JSON.parse(localStorage.getItem('bindProInfo')).productName ? JSON.parse(localStorage.getItem('bindProInfo')).productName : '';
		this.state = {
			queryData: {
        imeis: oQrcodeList,
        productKey: oProductKey,
        productName: oProductName,
      },
      timer: '',
      testFlag:false
		};
  }

  componentWillMount() {
    const { queryData } = this.state;
    const { testDevice, productId } = this.props;
    const { testType } = testDevice;
    this.query({ ...queryData, unitList: true, num: testType });
  }
  componentWillReceiveProps(nextProps) {
    const { testDevice, productId } = nextProps;
		const { isTesting, selectedRowKeys } = testDevice;
    const { queryData } = this.state;
    if (isTesting && queryData.imeis.length) {
      if (this.state.timer != null) {
        clearInterval(this.state.timer);
        this.state.timer = null;
      }
      this.state.timer = setInterval(() => {
        this.query({ ...queryData, num: 1 })
      }, 3000);
    } else {
      clearInterval(this.state.timer);
      this.state.timer = null;
    }
  }
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'testDevice/querySuccess',
      payload: {
        testType: 2
      },
    });
    if (this.state.timer != null) {
      clearInterval(this.state.timer);
      this.state.timer = null;
    }
  }
  // timeout = () => new Promise((resolve, reject) => {
  //   setTimeout(resolve, ms, 'done');
  // })
	query = (oData) => {
		const { dispatch } = this.props;
    dispatch({
      type: 'testDevice/query',
      payload: oData,
    });
  }
  toggleTest = () => {
    const { dispatch, testDevice } = this.props;
    const { isTesting, selectedRowKeys } = testDevice;
    const { queryData } = this.state;
    const { imeis } = queryData;
    if (!imeis.length) {
      Modal.warning({
        title: 'warning',
        content: '暂无需要测试设备',
      });
      return;
    }
    dispatch({
      type: 'testDevice/querySuccess',
      payload: {
        isTesting: !isTesting
      },
    });
  }
  onSelect = keys => {
    this.props.dispatch({
      type: 'testDevice/querySuccess',
      payload: {
        selectedRowKeys: keys
      }
    });
  }
  handlePass = (oArr, flag) => {
		// oArr：当批量操作时为空 单个操作则为[该emei]
    const { testDevice, dispatch } = this.props;
    const { selectedRowKeys } = testDevice;
    const { queryData } = this.state;
		const { imeis } = queryData;
		const oEmei = oArr ? [...oArr] : [...selectedRowKeys];
    this.props.dispatch({
      type: 'testDevice/operation',
      payload: {
        imeis: oEmei,
        isPass: flag
      }
    });
    oEmei.forEach((item, i) => {
      if ((imeis).indexOf(item) > -1) {
        imeis.splice((imeis).indexOf(item), 1);
      }
    });
    if (!imeis.length) {
      dispatch({
        type: 'testDevice/querySuccess',
        payload: {
          isTesting: false
        },
      });
    }
  }
  reset = () => {
    const { dispatch } = this.props;
    localStorage.setItem('qrcodeList', '[]');
    localStorage.setItem('bindProInfo', '{}');
    dispatch({
      type: 'testDevice/set',
      payload: {
				isTesting: false,
				list: []
      },
    });
    this.setState({
      queryData: {
        imeis: '',
        productKey: '',
        productName: '',
      },
      timer: '',
    });
    // this.query({
    //   queryData: {
    //     imeis: '',
    //     productKey: '',
    //     productName: '',
    //     num: '1'
    //   },
    //   timer: '',
    // });
  }

	render() {
		const { testDevice, productList, productId } = this.props;
		const { selectedRowKeys, list, pagination, isTesting } = testDevice;
    // const { current, pageSize, total } = pagination;
    const currentProduct = productList.find((item) => {
      return item.id === productId;
    }) || {};
    const productKey = currentProduct.gizwitsProductKey;
    return (
			<div className="content-inner">
				<Filter
          toggleTest={this.toggleTest}
          isTesting={isTesting}
          handlePass={this.handlePass}
          reset={this.reset}
    />
				<Table
          list={list}	
        // list={{list}||{firstList}}					
          select={this.onSelect}
					edit={this.goToDetail}
          handlePass={this.handlePass}
					selectKeys={selectedRowKeys}
					exportTitle="productExport"
          pagination={false}
          productKey={productKey}
				/>
			</div>
		);
	}
}

export default connect(
	({ testDevice, loading, app: { productId }, productList: { list: productList } }) => ({ testDevice, loading, productId, productList })
)(ProductList);
